package com.clwl.supervise.superviseapp.service.inspect;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.clwl.supervise.superviseapp.entity.base.CommonSearchEntity;
import com.clwl.supervise.superviseapp.entity.base.TcCompany;
import com.clwl.supervise.superviseapp.entity.base.TsDept;
import com.clwl.supervise.superviseapp.entity.base.TsUser;
import com.clwl.supervise.superviseapp.entity.base.rectificationSituationData.ContentList;
import com.clwl.supervise.superviseapp.entity.base.rectificationSituationData.ItemList;
import com.clwl.supervise.superviseapp.entity.base.rectificationSituationData.RectificationSituationData;
import com.clwl.supervise.superviseapp.entity.supervise.*;
import com.clwl.supervise.superviseapp.mapper.base.TcCompanyMapper;
import com.clwl.supervise.superviseapp.mapper.base.TsDeptMapper;
import com.clwl.supervise.superviseapp.mapper.base.TsUserMapper;
import com.clwl.supervise.superviseapp.mapper.supervise.*;
import com.clwl.supervise.superviseapp.service.base.BaseDataService;
import com.clwl.supervise.superviseapp.util.RedisUtil;
import com.clwl.supervise.superviseapp.util.UserHelper;
import com.clwl.supervise.superviseapp.util.file.FileResultEntity;
import com.clwl.supervise.superviseapp.util.file.FileUploadEnum;
import com.clwl.supervise.superviseapp.util.file.FileUploadUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 双随机检查
 */
@Service
@Slf4j
public class DoubleRandomCheckService {

    @Resource
    private RedisUtil redisUtil;
    @Resource
    private JgRandomCompanyMapper randomCompanyMapper;
    @Resource
    private TsDeptMapper deptMapper;
    @Resource
    private JgDailyCheckMapper dailyCheckMapper;
    @Resource
    private TsUserMapper userMapper;
    @Resource
    private TcCompanyMapper companyMapper;

    @Resource
    private JgTemplateMapper templateMapper;
    @Resource
    private JgCheckContentMapper jgCheckContentMapper;
    @Resource
    private JgCheckMissingMapper jgCheckMissingMapper;
    @Resource
    private JgCheckProblemMapper jgCheckProblemMapper;
    @Resource
    private JgDailyStandardMapper jgDailyStandardMapper;
    @Resource
    private JgStandardMapper jgStandardMapper;
    @Resource
    private JgDailyContentMapper jgDailyContentMapper;
    @Resource
    private JsEntAnomalyMapper jsEntAnomalyMapper;
    @Resource
    private JgRectificationMapper rectificationMapper;
    @Resource
    private JgRectificationContentMapper rectificationContentMapper;
    @Resource
    private JgInvestigationSetMapper jgInvestigationSetMapper;
    @Resource
    private JgInvestigationMapper investigationMapper;
    @Resource
    private JgInvestigationContentMapper investigationContentMapper;
    @Resource
    private JgCheckInformMapper jgCheckInformMapper;
    @Resource
    private BaseDataService baseDataService;


    /**
     * 获取日常检查的企业列表
     *
     * @param pageNum  当前页数
     * @param pageSize 每页数据数量
     * @return
     */

    @Transactional(readOnly = true)
    public IPage<Map<String, Object>> selectDoubleRandomCheckPage(Integer pageNum, Integer pageSize, CommonSearchEntity commonSearchEntity) {
        commonSearchEntity.setUserId(UserHelper.getUserId());
        commonSearchEntity.setDataRange(UserHelper.getUserInfo().getDataRange());
        commonSearchEntity.setDeptId(UserHelper.getUserInfo().getDeptId());
        Page<Map<String, Object>> iPage = Page.of(pageNum, pageSize);
        iPage.setOptimizeCountSql(false);
        iPage.setSearchCount(false);
        IPage<Map<String, Object>> pageList = randomCompanyMapper.selectDoubleRandomCheckPage(iPage, commonSearchEntity);
        return pageList;
    }


    /**
     * 检查结果
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    public IPage<Map<String, Object>> selectInspectionResultPage(Integer pageNum, Integer pageSize, CommonSearchEntity commonSearchEntity) {
        commonSearchEntity.setUserId(UserHelper.getUserId());
        commonSearchEntity.setDataRange(UserHelper.getUserInfo().getDataRange());
        commonSearchEntity.setDeptId(UserHelper.getUserInfo().getDeptId());
        Page<Map<String, Object>> iPage = Page.of(pageNum, pageSize);
        iPage.setOptimizeCountSql(false);
        iPage.setSearchCount(false);
        return randomCompanyMapper.selectInspectionResultPage(iPage, commonSearchEntity);

    }

    /**
     * 获取企业相关信息
     *
     * @param companyId
     * @return
     */
    public Map<String, Object> selectCompanyInfo(Long companyId) {
        Map<String, Object> companyInfo = companyMapper.selectCompanyInspectionInfo(companyId);
        JgDailyCheck dailyCheck = getJgDailyCheck(companyId);
        //经营状态;0正常，1异常
        companyInfo.put("CHECK_TIME", dailyCheck.getCheckTime());
        companyInfo.put("MANAGE_STATUS", dailyCheck.getManageStatus() == null ? "0" : dailyCheck.getManageStatus());
        companyInfo.put("COMANY_PIC", dailyCheck.getComanyPic());
        companyInfo.put("CHECK_RESULTS", dailyCheck.getCheckResult() == null ? "1" : dailyCheck.getCheckResult());
        companyInfo.put("OTHER_PROBLEM", dailyCheck.getOtherProblem() == null ? "" : dailyCheck.getOtherProblem());
        companyInfo.put("ABNORMAL_CAUSE", dailyCheck.getAbnormalCause());
        companyInfo.put("PROCESS_RESULTS", dailyCheck.getProcessResults());
        //获取主体异常信息
        JsEntAnomaly jsEntAnomaly = jsEntAnomalyMapper.selectByCompanyAndDailyCheck(companyId, dailyCheck.getId());
        if (jsEntAnomaly != null) {
            companyInfo.put("AUDIT_TRAILS", jsEntAnomaly.getAuditTrails());
            companyInfo.put("RECTIFY_TIME", jsEntAnomaly.getRectifyTime());
        }
        log.info("companyInfo:{}", companyInfo);
        Long deptId = UserHelper.getUserInfo().getDeptId();
        TsDept dept = deptMapper.selectById(deptId);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("deptName", dept.getName());
        resultMap.put("checkId", dailyCheck == null ? null : dailyCheck.getId());
        resultMap.put("checkItemTableUrl", dailyCheck.getCheckItemTableUrl());
        resultMap.put("resultRecordUrl", dailyCheck.getResultRecordUrl());
        resultMap.put("informUrl", dailyCheck.getInformUrl());
      /*  TcCompany company = companyMapper.selectById(companyId);
        Long userId = UserHelper.getUserInfo().getId();
        Long legalHead1Id = dailyCheck.getCheckPerson1Id() == null ? company.getLegalHead1Id() : dailyCheck.getCheckPerson1Id();
        String legalHead1Name = dailyCheck.getCheckPerson1Name() == null ? company.getLegalHead1Name() : dailyCheck.getCheckPerson1Name();
        Long legalHead2Id = dailyCheck.getCheckPerson2Id() == null ? company.getLegalHead2Id() : dailyCheck.getCheckPerson2Id();
        String legalHead2Name = dailyCheck.getCheckPerson2Name() == null ? company.getLegalHead2Name() : dailyCheck.getCheckPerson2Name();
        if(StringUtils.equals(legalHead1Id+"",legalHead2Id+"")){
            //防止监管人1中的存储的数据是监管人2 导致的两个监管人信息相同
            legalHead2Id = company.getLegalHead1Id();
            legalHead2Name = company.getLegalHead1Name();
        }
        //当前登录人是监管人的情况下，那么页面显示的第一监管人是当前人,第二监管人则是另一个网格负责人
        resultMap.put("checkPerson1Id",StringUtils.equals(userId+"",legalHead1Id+"")  ? legalHead1Id : (StringUtils.equals(userId+"",legalHead2Id+"") ? legalHead2Id : legalHead1Id));
        resultMap.put("checkPerson1Name",StringUtils.equals(userId+"",legalHead1Id+"")? legalHead1Name : (StringUtils.equals(userId+"",legalHead2Id+"") ? legalHead2Name : legalHead1Name));
        resultMap.put("checkPerson2Id",StringUtils.equals(userId+"",legalHead1Id+"") ? legalHead2Id : (StringUtils.equals(userId+"",legalHead2Id+"") ? legalHead1Id : legalHead2Id));
        resultMap.put("checkPerson2Name", StringUtils.equals(userId+"",legalHead1Id+"") ? legalHead2Name : (StringUtils.equals(userId+"",legalHead2Id+"") ? legalHead1Name : legalHead2Name));*/
        companyInfo.putAll(resultMap);
        return companyInfo;

    }

    /**
     * 获取企业相关信息
     *
     * @param companyId
     * @return
     */
    public Map<String, Object> selectCheckInfo(Long companyId) {
        Map<String, Object> companyInfo = companyMapper.selectCompanyInspectionInfo(companyId);
        JgDailyCheck dailyCheck = getJgDailyCheck(companyId);
        //经营状态;0正常，1异常
        companyInfo.put("CHECK_TIME", dailyCheck.getCheckTime());
        companyInfo.put("MANAGE_STATUS", dailyCheck.getManageStatus() == null ? "0" : dailyCheck.getManageStatus());
        companyInfo.put("COMANY_PIC", dailyCheck.getComanyPic());
        companyInfo.put("CHECK_RESULTS", dailyCheck.getCheckResult() == null ? "1" : dailyCheck.getCheckResult());
        companyInfo.put("OTHER_PROBLEM", dailyCheck.getOtherProblem() == null ? "" : dailyCheck.getOtherProblem());
        companyInfo.put("PROCESS_RESULTS", dailyCheck.getProcessResults());
        companyInfo.put("ABNORMAL_CAUSE", dailyCheck.getAbnormalCause());
        //获取主体异常信息
        JsEntAnomaly jsEntAnomaly = jsEntAnomalyMapper.selectByCompanyAndDailyCheck(companyId, dailyCheck.getId());
        if (jsEntAnomaly != null) {
            companyInfo.put("AUDIT_TRAILS", jsEntAnomaly.getAuditTrails());
            companyInfo.put("RECTIFY_TIME", jsEntAnomaly.getRectifyTime());
        }
        log.info("companyInfo:{}", companyInfo);
        Long deptId = UserHelper.getUserInfo().getDeptId();
        TsDept dept = deptMapper.selectById(deptId);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("deptName", dept.getName());
        resultMap.put("checkId", dailyCheck == null ? null : dailyCheck.getId());
        resultMap.put("checkItemTableUrl", dailyCheck.getCheckItemTableUrl());
        resultMap.put("resultRecordUrl", dailyCheck.getResultRecordUrl());
        resultMap.put("informUrl", dailyCheck.getInformUrl());
        //当前登录人是监管人的情况下，那么页面显示的第一监管人是当前人,第二监管人则是另一个网格负责人
        resultMap.put("checkPerson1Id", dailyCheck.getCheckPerson1Id());
        resultMap.put("checkPerson1Name", dailyCheck.getCheckPerson1Name());
        resultMap.put("checkPerson2Id", dailyCheck.getCheckPerson2Id());
        resultMap.put("checkPerson2Name", dailyCheck.getCheckPerson2Name());
        Map<String, Object> result = new HashMap<>();
        result.put("superviseInfo", resultMap);
        result.put("companyInfo", companyInfo);
        return result;

    }

    /**
     * 获取检查内容以及填写过的检查内容
     *
     * @param checkId
     * @return
     */
    public List<Map<String, Object>> selectCheckItemList(Long checkId, Long companyId) {
        JgDailyCheck dailyCheck = dailyCheckMapper.selectById(checkId);
        TcCompany company = companyMapper.selectById(companyId);
        if (!("spsc".equals(company.getSupProcess()) || "tssc".equals(company.getSupProcess())) && company.getCompanyTypeId() == null) {
            throw new RuntimeException("企业业态信息为空,无法获取检查内容!");
        }

        //获取企业的风险信息
        Map<String, String> riskMap = baseDataService.riskInfo(companyId);
        List<String> riskCode = new ArrayList<>();
        Set<String> riskKeySet = riskMap.keySet();
        for (String riskKey : riskKeySet) {
            if (!riskMap.get(riskKey).equals("0")) {
                riskCode.add(riskKey);
            }
        }

        String supProcess = company.getSupProcess();
        //查看当前企业是否之前填写了检查信息
        try {
            if (dailyCheck == null) {
                //标准列表
                List<Map<String, Object>> checkStandardList = templateMapper.selectStandardListBySupProcess(supProcess, company.getCompanyTypeId());
                List<Map<String, Object>> checkMissingListAll = jgCheckMissingMapper.selectMapList();
                List<Map<String, Object>> checkProblemListAll = jgCheckProblemMapper.selectMapList();
                for (Map<String, Object> checkStandard : checkStandardList) {
                    //获取标准中检查内容
                    List<Map<String, Object>> contentList = jgCheckContentMapper.selectByStandardId(checkStandard.get("TEPLATE_STANDARD_ID"));
                    for (Map<String, Object> content : contentList) {
                        //获取content的检查说明选项
                        List<Map<String, Object>> checkMissingList = checkMissingListAll.stream().filter(map -> StringUtils.equals(content.get("ID") + "", map.get("CONTENT_ID") + "")).collect(Collectors.toList());
//                        jgCheckMissingMapper.selectByContentId(content.get("ID"));
                        content.put("checkMissingList", checkMissingList);
                        //获取content的问题描述选项CONTENT_ID
                        List<Map<String, Object>> checkProblemList = checkProblemListAll.stream().filter(map -> StringUtils.equals(content.get("ID") + "", map.get("CONTENT_ID") + "")).collect(Collectors.toList());
                        //jgCheckProblemMapper.selectByContentId(content.get("ID"));
                        content.put("PROBLEM_PRE_TYPE", content.get("PROBLEM_PRE_TYPE"));
//                        content.put("PROBLEM_CONTENT","自定义备注");
                        if (StringUtils.equals("1", content.get("PROBLEM_PRE_TYPE") + "")) {
                            //多选的情况下处理
                            for (Map<String, Object> map : checkProblemList) {
                                map.put("is_selected", false);
                                if (content.get("PROBLEM_CONTENT") != null) {
                                    String[] problemArr = String.valueOf(content.get("PROBLEM_CONTENT")).split("##");
                                    for (String problem : problemArr) {
                                        if (problem.equals(String.valueOf(map.get("DESCRIPTION")))) {
                                            map.put("is_selected", true);
                                        }
                                    }
                                }
                            }
                        }
                        content.put("checkProblemList", checkProblemList);
                    }
                    checkStandard.put("contentList", contentList);
                }
                return checkStandardList;
            } else {
                //获取已经填写的检查内容

                List<Map<String, Object>> checkMissingListAll = jgCheckMissingMapper.selectMapList();
                List<Map<String, Object>> checkProblemListAll = jgCheckProblemMapper.selectMapList();
                //标准列表
                List<Map<String, Object>> checkStandardList = jgDailyStandardMapper.selectStandardList(supProcess, company.getCompanyTypeId(), dailyCheck.getId(), "1");
                for (Map<String, Object> checkStandard : checkStandardList) {
                    //获取标准中检查内容
                    //log.info("已经存在的检查结果获取历史检查数据,TEPLATE_STANDARD_ID:{},DAILT_STANDARD_ID:{}", checkStandard.get("TEPLATE_STANDARD_ID"), checkStandard.get("DAILT_STANDARD_ID"));
                    List<Map<String, Object>> contentList = jgDailyContentMapper.selectByStandardId(checkStandard.get("TEPLATE_STANDARD_ID"), checkStandard.get("DAILT_STANDARD_ID"), riskCode);
                    for (Map<String, Object> content : contentList) {
                        //获取content的检查说明选项
                        List<Map<String, Object>> checkMissingList = checkMissingListAll.stream().filter(map -> StringUtils.equals(content.get("ID") + "", map.get("CONTENT_ID") + "")).collect(Collectors.toList());
//                        jgCheckMissingMapper.selectByContentId(content.get("ID"));
                        content.put("checkMissingList", checkMissingList);
                        //获取content的问题描述选项CONTENT_ID
                        List<Map<String, Object>> checkProblemList = checkProblemListAll.stream().filter(map -> StringUtils.equals(content.get("ID") + "", map.get("CONTENT_ID") + "")).collect(Collectors.toList());
                        //jgCheckProblemMapper.selectByContentId(content.get("ID"));
                        content.put("PROBLEM_PRE_TYPE", content.get("PROBLEM_PRE_TYPE"));
//                        content.put("PROBLEM_CONTENT","自定义备注");
                        if (StringUtils.equals("1", content.get("PROBLEM_PRE_TYPE") + "")) {
                            //多选的情况下处理
                            for (Map<String, Object> map : checkProblemList) {
                                map.put("is_selected", false);
                                if (content.get("PROBLEM_CONTENT") != null) {
                                    String[] problemArr = String.valueOf(content.get("PROBLEM_CONTENT")).split("##");
                                    for (String problem : problemArr) {
                                        if (problem.equals(String.valueOf(map.get("DESCRIPTION")))) {
                                            map.put("is_selected", true);
                                        }
                                    }
                                }
                            }
                        }
                        content.put("checkProblemList", checkProblemList);
                    }
                    checkStandard.put("contentList", contentList);
                }
                return checkStandardList;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("获取检查信息失败!");
        }

    }

    /**
     * 获取双随机检查的历史信息
     *
     * @param companyId
     * @return
     */
    public JgDailyCheck getJgDailyCheck(Long companyId) {
        synchronized ((companyId + "").intern()) {
            List<JgDailyCheck> dailyCheckList = dailyCheckMapper.selectByCompanyIdAndYearAndType(companyId, DateUtil.format(new Date(), "yyyy"), "2");
            TcCompany company = companyMapper.selectById(companyId);
            TsDept dept = null;
            if (UserHelper.getUserInfo().getDeptId() != null) {
                dept = deptMapper.selectById(UserHelper.getUserInfo().getDeptId());
            }
            //创建日检查单子
            JgDailyCheck dailyCheck = dailyCheckList.isEmpty() ? new JgDailyCheck() : dailyCheckList.get(0);
            JgTemplate template = templateMapper.selectBySupProcess(company.getSupProcess(), company.getCompanyTypeId(), "1");
            if (template == null) {
                throw new RuntimeException("检查模板为空");
            }
            dailyCheck.setTemplateId(template.getId());
            dailyCheck.setTemplateName(template == null ? "" : template.getName());
            dailyCheck.setDeptId(UserHelper.getUserInfo().getDeptId());
            if (dept != null) {
                dailyCheck.setDeptName(dept.getName());
                dailyCheck.setCreateDeptId(UserHelper.getUserInfo().getDeptId());
                dailyCheck.setCreateDeptName(dept.getName());
            }
            //dailyCheck.setCheckTime(DateUtil.format(new Date(),"yyyy-MM-dd"));
            dailyCheck.setCompanyId(companyId);
            dailyCheck.setCompanyName(company.getCompanyName());
            dailyCheck.setCreditCode(company.getCreditCode());
            dailyCheck.setLicense(company.getLicense());
            dailyCheck.setComanyPic(company.getComanyPic());
            dailyCheck.setComanyThumbnail(company.getComanyThumbnail());
            int checkNum = getCheckNum(companyId);
            dailyCheck.setCheckNum(Long.valueOf(checkNum));
            dailyCheck.setCheckYear(Long.valueOf(DateUtil.format(new Date(), "yyyy")));
            dailyCheck.setCheckStat("3");
            dailyCheck.setCreateTime(new Date());
            dailyCheck.setCreatorId(UserHelper.getUserId());
            dailyCheck.setCreator(UserHelper.getUserInfo().getName());
            dailyCheck.setDeleteFlag(0L);
            dailyCheck.setType("2");
            dailyCheck.setIsUnplanned("0");
            dailyCheck.setIsTempUnplanned("0");
            JgRandomCompany randomCompany = randomCompanyMapper.selectByYearAndCompanyId(String.valueOf(DateUtil.year(new Date())), companyId);
            dailyCheck.setCheckPerson1Id(randomCompany.getLegalHead1Id() != null ? Long.parseLong(randomCompany.getLegalHead1Id()) : 0L);
            dailyCheck.setCheckPerson1Name(randomCompany.getLegalHead1Name() != null ? randomCompany.getLegalHead1Name() : "");
            dailyCheck.setCheckPerson2Id(randomCompany.getLegalHead2Id() != null ? Long.parseLong(randomCompany.getLegalHead2Id()) : 0L);
            dailyCheck.setCheckPerson2Name(randomCompany.getLegalHead2Name() != null ? randomCompany.getLegalHead2Name() : "");
            //再次确认是否已经存在
            List<JgDailyCheck> dailyCheckListQ = dailyCheckMapper.selectByCompanyIdAndYearAndType(companyId, DateUtil.format(new Date(), "yyyy"), "2");
            if (dailyCheck.getId() == null && dailyCheckListQ.isEmpty()) {
                dailyCheckMapper.insert(dailyCheck);
            }
            return dailyCheck;
        }
    }

    /**
     * 保存检查项结果内容
     *
     * @param checkId                 检查Id
     * @param standardId              检查标准id
     * @param contentId               检查内容Id
     * @param result                  选择的结果
     * @param problemContent          问题描述
     * @param checkExplain            检查说明
     * @param problemContentInput     问题描述输入的内容
     * @param missingItemContentInput 检查说明输入的内容
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveCheckItem(Long checkId, Long standardId, Long contentId, String result, String problemContent, String checkExplain, String problemContentInput, String missingItemContentInput) {
        //用redis保证数据请求唯一性
        // if (redisUtil.get(checkId + UserHelper.getUserId() + contentId + "ssj") != null) {
        //     throw new RuntimeException("操作的太快啦!");
        // }
        //  redisUtil.set(checkId + UserHelper.getUserId() + contentId + "ssj", result, 1l);
        //检查是否已经存在日常检查的信息
        JgDailyCheck dailyCheck = dailyCheckMapper.selectById(checkId);
        TcCompany company = companyMapper.selectById(dailyCheck.getCompanyId());

        TsDept dept = null;
        if (UserHelper.getUserInfo().getDeptId() != null) {
            dept = deptMapper.selectById(UserHelper.getUserInfo().getDeptId());
        }
        //获取有没有此项的DailyStandard
        JgDailyStandard dailyStandard = jgDailyStandardMapper.selectStandard(standardId, dailyCheck.getId());
        JgStandard jgStandard = jgStandardMapper.selectById(standardId);
        if (dailyStandard == null) {
            //创建保存的标准信息
            dailyStandard = new JgDailyStandard();
            dailyStandard.setTemplateId(dailyCheck.getTemplateId());
            dailyStandard.setStandardId(standardId);
            dailyStandard.setSupCategory("1");
            dailyStandard.setSupProcess(company.getSupProcess());
            dailyStandard.setSpxsId(jgStandard.getSpxsId());
            dailyStandard.setCyfwId(jgStandard.getCyfwId());
            dailyStandard.setSpscLbId(jgStandard.getSpscLbId());
            dailyStandard.setSpscLbZlId(jgStandard.getSpscLbZlId());
            dailyStandard.setTsspLbId(jgStandard.getTsspLbId());
            dailyStandard.setTsspLbZlId(jgStandard.getTsspLbZlId());
            dailyStandard.setName(jgStandard.getName());
            dailyStandard.setSerialNum(jgStandard.getSerialNum());
            dailyStandard.setDailyCheckId(dailyCheck.getId());
            dailyStandard.setCreateTime(new Date());
            dailyStandard.setCreatorId(UserHelper.getUserId());
            dailyStandard.setCreator(UserHelper.getUserInfo().getName());
            if (dept != null) {
                dailyStandard.setCreateDeptName(dept.getName());
                dailyStandard.setCreateDeptId(UserHelper.getUserInfo().getDeptId());
            }
            dailyStandard.setDeleteFlag(0L);
            jgDailyStandardMapper.insert(dailyStandard);
        }
        //获取此项检查内容是否已经填写过
        JgDailyContent dailyContent = jgDailyContentMapper.selectByContentAndDailyStandard(contentId, dailyStandard.getId(), new ArrayList<>());

        JgCheckContent content = jgCheckContentMapper.selectById(contentId);
        if (dailyContent == null) {
            dailyContent = new JgDailyContent();
            dailyContent.setContentId(contentId);
            dailyContent.setDailyStandardId(dailyStandard.getId());
            dailyContent.setCreateTime(new Date());
            dailyContent.setCreatorId(UserHelper.getUserId());
            dailyContent.setCreator(UserHelper.getUserInfo().getName());
            if (dept != null) {
                dailyContent.setCreateDeptId(dept.getId());
                dailyContent.setCreateDeptName(dept.getName());
            }
            dailyContent.setDeleteFlag(0L);
            dailyContent.setCheckContent(content.getCheckContent());
            dailyContent.setImportentItem(content.getImportentItem());
            dailyContent.setSerialNum(content.getSerialNum());
            dailyContent.setMissingItem(content.getMissingItem());
            dailyContent.setRemark(content.getRemark());
        }
        if ("1".equals(result)) {
            dailyContent.setScore(content.getYesScore());
        } else {
            dailyContent.setScore(content.getScore());
        }
        dailyContent.setSelection(result);
        dailyContent.setMissingItemContent(checkExplain);
        dailyContent.setProblemContent(problemContent);
        dailyContent.setProblemContentInput(problemContentInput);
        dailyContent.setMissingItemContentInput(missingItemContentInput);
        dailyContent.setMissingItemContent(checkExplain);
        if (dailyContent.getId() == null) {
            jgDailyContentMapper.insert(dailyContent);
        } else {
            jgDailyContentMapper.updateById(dailyContent);
        }
    }

    /**
     * 计算该企业应该第几次检查
     *
     * @param companyId
     * @return
     */
    public int getCheckNum(Long companyId) {
        //获取当前该企业日常检查应该到哪次
        List<JgDailyCheck> readyCheckList = dailyCheckMapper.selectReadyByCompanyId(companyId);
        List<Long> checkNumList = new ArrayList<>();
        for (JgDailyCheck check : readyCheckList) {
            checkNumList.add(check.getCheckNum());
        }
        int checkNum = 0;
        log.info("获取到之前企业已经检查的日常任务次数:{}", checkNumList);
        log.info("获取到之前企业已经检查的日常任务个数", checkNumList.size());
        if (checkNumList.size() > 0) {
            Long maxCheckNum = checkNumList.get(checkNumList.size() - 1);
            log.info("获取到之前企业已经检查的日常任务最大次数", maxCheckNum);

            for (int i = 1; i <= maxCheckNum; i++) {
                if (!checkNumList.contains(i)) {
                    //如果在1到最大次数之间有一次没有，则双随机算到这个次数中
                    //如果该次数有之前检查完未保存的情况，则将原来未保存的那个删除
                    checkNum = i;
                }
            }
            if (checkNum == 0) {
                //说明for循环中没有匹配上，说明中间的次数都已经检查完成，此时在最大的次数上加1
                checkNum = Integer.parseInt(maxCheckNum + "");
            }
        } else {
            //如果没有已经检查的次数，则就抵用日常检查的第一次
            checkNum = 1;
        }
        log.info("抵用日常检查次数:{}", checkNum);
        //如果该次数有日常检查未保存则删除该日常检查保存的信息
        List<JgDailyCheck> dailyCheckList = dailyCheckMapper.selectByCompanyIdAndCheckNumAndYearAndType(companyId, checkNum, DateUtil.format(new Date(), "yyyy"), "1");
        for (JgDailyCheck dailyCheck : dailyCheckList) {
            dailyCheck.setDeleteFlag(1L);
            dailyCheckMapper.updateById(dailyCheck);
        }
        return checkNum;
    }

    /**
     * 保存检查门头照照片
     *
     * @param checkId
     * @param file
     * @return
     * @throws IOException
     */
    @Transactional(rollbackFor = Exception.class)
    public JgDailyCheck uploadCheckFile(Long checkId, MultipartFile file) throws Exception {
        JgDailyCheck dailyCheck = dailyCheckMapper.selectById(checkId);
        FileResultEntity fileEntity = FileUploadUtil.uploadImage(file, FileUploadEnum.doubleRandomInspect.getPath());
        dailyCheck.setComanyPic(fileEntity.getFilePath());
        dailyCheck.setComanyThumbnail(fileEntity.getFileThPath());
        dailyCheckMapper.updateById(dailyCheck);
        return dailyCheck;
    }

    /**
     * 上传检查项的问题照片
     *
     * @param checkId    检查Id
     * @param standardId 检查标准id
     * @param contentId  检查内容Id
     * @param file
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String uploadItemFile(Long checkId, Long standardId, Long contentId, MultipartFile file) {
        try {
            JgDailyCheck dailyCheck = dailyCheckMapper.selectById(checkId);
            JgDailyStandard dailyStandard = jgDailyStandardMapper.selectStandard(standardId, dailyCheck.getId());
            JgDailyContent dailyContent = jgDailyContentMapper.selectByContentAndDailyStandard(contentId, dailyStandard.getId(), new ArrayList<>());
            dailyContent.setProblemFile(FileUploadUtil.uploadFile(file, FileUploadEnum.doubleRandomInspect.getPath()).getFilePath());
            jgDailyContentMapper.updateById(dailyContent);
            return dailyContent.getProblemFile();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("上传文件失败!");
        }
    }

    /**
     * 保存/临时保存检查项结果内容
     *
     * @param checkId                检查id
     * @param manageStatus           经营状态：0正常，1异常
     * @param abnormalCause          异常原因
     * @param auditTrails            异常核查记录
     * @param rectifyTime            异常整改时间
     * @param checkResults           异常检查结果
     * @param exprocessResults       异常处理结果
     * @param companyPic             门头照(file标签的文件二进制流)
     * @param processResults         检查处理结果：1通过检查，2责令整改，3调查处理
     * @param otherProblem           其他问题
     * @param temporary              是否临时1-是；2-否
     * @param rectificationTimeLimit 整改时限
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JgDailyCheck saveCheckInfo(Long checkId, String manageStatus, String abnormalCause, String auditTrails, String rectifyTime, String checkResults, String exprocessResults, MultipartFile companyPic, String processResults, String otherProblem, String temporary,
                                      String rectificationTimeLimit, RectificationSituationData rectificationSituationData, String contactPhone) {
        JgDailyCheck dailyCheck = dailyCheckMapper.selectById(checkId);
        TcCompany company = companyMapper.selectById(dailyCheck.getCompanyId());
        if ("2".equals(temporary)) {
            dailyCheck.setCheckTime(DateUtil.format(new Date(), "yyyy-MM-dd"));
            dailyCheck.setCheckStat("1");
        } else {
            dailyCheck.setCheckStat("3");
        }
        JgRandomCompany jgcompany = randomCompanyMapper.selectByYearAndCompanyId(DateUtil.format(new Date(), "yyyy"), dailyCheck.getCompanyId());
        if (jgcompany != null) {
            dailyCheck.setCheckPerson1Name(StringUtils.defaultIfEmpty(jgcompany.getLegalHead1Name(), "") + StringUtils.defaultIfEmpty(jgcompany.getLegalHead1No(), ""));
            dailyCheck.setCheckPerson2Name(StringUtils.defaultIfEmpty(jgcompany.getLegalHead2Name(), "") + StringUtils.defaultIfEmpty(jgcompany.getLegalHead2No(), ""));
        }
        if (companyPic != null && StringUtils.isNoneBlank(companyPic.getOriginalFilename())) {
            FileResultEntity fileResultEntity = null;
            try {
                fileResultEntity = FileUploadUtil.uploadImage(companyPic, FileUploadEnum.doubleRandomInspect.getPath());
            } catch (Exception e) {
                throw new RuntimeException("上传文件失败");
            }
            dailyCheck.setComanyPic(fileResultEntity.getFilePath());
            dailyCheck.setComanyThumbnail(fileResultEntity.getFileThPath());
        }
        dailyCheck.setCheckResult(checkResults);
        dailyCheck.setManageStatus(manageStatus);
        if (StringUtils.isNotBlank(rectificationTimeLimit)) {
            dailyCheck.setRectificationTimeLimit(rectificationTimeLimit);
        }
        if ("1".equals(manageStatus)) {
            //如果选择的是异常的话，默认就是整改
            processResults = "2";
        }
        dailyCheck.setProcessResults(processResults);
        dailyCheck.setOtherProblem(otherProblem);
        dailyCheckMapper.updateById(dailyCheck);
        TsDept dept = null;
        if (UserHelper.getUserInfo().getDeptId() != null) {
            dept = deptMapper.selectById(UserHelper.getUserInfo().getDeptId());
        }
        //保存检查内容列表信息
        saveItemListAndContentList(rectificationSituationData, dailyCheck, company, dept, manageStatus, abnormalCause,
                auditTrails, rectifyTime, checkResults, exprocessResults, temporary);

        if ("2".equals(temporary) || "1".equals(manageStatus)) {
            //正式保存或经营异常直接完成保存
            dailyCheck = finaSaveInfo(dailyCheck.getId(), dailyCheck.getProcessResults(), dailyCheck.getRectificationTimeLimit(), contactPhone);
        }
        //保存异常信息
        if ("1".equals(manageStatus)) {
//            dailyCheckService.saveEntAnomaly(jsEntAnomalyMapper, templateMapper, jgCheckContentMapper, jgDailyStandardMapper, jgDailyContentMapper, company, dailyCheck, abnormalCause,
//                    auditTrails, rectifyTime, checkResults, exprocessResults, rectificationTimeLimit,temporary);
            saveEntAnomaly(company, dailyCheck, exprocessResults, auditTrails, rectifyTime, checkResults, exprocessResults);

        }
        return dailyCheck;
    }


    /**
     * 最终保存的时候保存检查内容
     *
     * @param rectificationSituationData
     * @param dailyCheck
     * @param company
     * @param dept
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveItemListAndContentList(
            RectificationSituationData rectificationSituationData, JgDailyCheck dailyCheck, TcCompany company, TsDept dept, String manageStatus, String abnormalCause,
            String auditTrails, String rectifyTime, String checkResults, String exprocessResults, String temporary) {

        List<JgDailyStandard> dailyStandardList = jgDailyStandardMapper.selectStandardByCheckId(dailyCheck.getId());
        List<ItemList> itemList = rectificationSituationData.getItemList();
        List<Long> standardIdList = itemList.stream().map(ItemList::getId).collect(Collectors.toList());
        List<JgStandard> itemQueryList = jgStandardMapper.selectBatchIds(standardIdList);
        //获取所有页面传来的检查小项
        List<JgDailyContent> queryDailyContenList = jgDailyContentMapper.selectEntityByDailyCheckId(dailyCheck.getId());
        // 1. 收集需要新增的 dailyStandard
        List<JgDailyStandard> newStandards = new ArrayList<>();
        Map<Long, JgDailyStandard> standardIdToDailyStandard = new HashMap<>(); // 标准ID到DailyStandard的映射
        for (JgStandard standard : itemQueryList) {
            Optional<JgDailyStandard> existing = dailyStandardList.stream()
                    .filter(ds -> Objects.equals(ds.getStandardId(), standard.getId()))
                    .findFirst();

            if (existing.isPresent()) {
                standardIdToDailyStandard.put(standard.getId(), existing.get());
            } else {
                JgDailyStandard dailyStandard = createNewDailyStandard(standard, dailyCheck, company, dept);
                newStandards.add(dailyStandard);
                // 先临时映射，插入后更新ID
                standardIdToDailyStandard.put(standard.getId(), dailyStandard);
            }
        }
        // 2. 批量插入新增的 dailyStandard（获取数据库生成的ID）
        if (!newStandards.isEmpty()) {
            jgDailyStandardMapper.batchInsert(newStandards); // 需确保 MyBatis 配置了 useGeneratedKeys
        }
        // 3. 准备 dailyContent 的批量操作
        List<JgDailyContent> insertContentList = new ArrayList<>();
        List<JgDailyContent> updateContentList = new ArrayList<>();


        // 4. 预构建 existingDailyContent 的映射（dailyStandardId + contentId → DailyContent）
        Map<Long, Map<Long, JgDailyContent>> existingContentMap = new HashMap<>();
        for (JgDailyContent dc : queryDailyContenList) {
            existingContentMap
                    .computeIfAbsent(dc.getDailyStandardId(), k -> new HashMap<>())
                    .put(dc.getContentId(), dc);
        }
        int checkNum = 0;
        // 5. 遍历处理每个 standard 的 content
        for (JgStandard standard : itemQueryList) {
            JgDailyStandard dailyStandard = standardIdToDailyStandard.get(standard.getId());
            Optional<ItemList> standardParamOp = itemList.stream()
                    .filter(item -> Objects.equals(item.getId(), standard.getId()))
                    .findFirst();
            List<ContentList> contentList = standardParamOp.isPresent() ? standardParamOp.get().getContentList() : new ArrayList<>();
            List<JgCheckContent> contentQueryList = jgCheckContentMapper.selectBatchIds(contentList.stream().map(ContentList::getId).collect(Collectors.toList()));
            for (ContentList content : contentList) {
                // 检查是否已存在 dailyContent
                Map<Long, JgDailyContent> contentIdMap = existingContentMap.getOrDefault(dailyStandard.getId(), new HashMap<>());
                JgDailyContent existingContent = contentIdMap.get(content.getId());
                JgCheckContent contentQuery = contentQueryList.stream().filter(contentQ -> Objects.equals(contentQ.getId(), content.getId())).findFirst().get();
                checkNum = checkNum + 1;
                JgDailyContent dailyContent;
                if (existingContent == null) {
                    // 创建新的 dailyContent
                    dailyContent = new JgDailyContent();
                    dailyContent.setContentId(content.getId());
                    dailyContent.setDailyStandardId(dailyStandard.getId());
                    dailyContent.setCreateTime(new Date());
                    dailyContent.setCreatorId(UserHelper.getUserId());
                    dailyContent.setCreator(UserHelper.getUserInfo().getName());
                    dailyContent.setCreateDeptId(UserHelper.getUserInfo().getDeptId());
                    dailyContent.setCreateDeptName(UserHelper.getUserInfo().getDeptName());
                    dailyContent.setDeleteFlag(0L);
                    dailyContent.setImportentItem(content.getImportentItem());
                    dailyContent.setSerialNum(content.getSerialNum());
                    dailyContent.setMissingItem(content.getMissingItem());
                    dailyContent.setRemark(contentQuery.getRemark());
                    setDailyContent(manageStatus, content, dailyContent, contentQuery);
                    insertContentList.add(dailyContent);
                } else {
                    // 更新现有 dailyContent
                    dailyContent = existingContent;
                    setDailyContent(manageStatus, content, dailyContent, contentQuery);
                    updateContentList.add(dailyContent);
                }

            }
        }

        // 6. 批量保存 dailyContent
        if (!insertContentList.isEmpty()) {
            jgDailyContentMapper.batchInsert(insertContentList);
        }
        if (!updateContentList.isEmpty()) {
            jgDailyContentMapper.batchUpdate(updateContentList);
        }


        if ("1".equals(manageStatus)) {
            //保存异常信息
            JsEntAnomaly jsEntAnomaly = jsEntAnomalyMapper.selectByCheckId(dailyCheck.getId(), "1");
            if (jsEntAnomaly == null) {
                jsEntAnomaly = new JsEntAnomaly();
            }
            jsEntAnomaly.setCheckType("1");
            jsEntAnomaly.setCompanyId(company.getId());
            jsEntAnomaly.setCompanyName(company.getCompanyName());
            jsEntAnomaly.setCreditCode(company.getCreditCode());
            jsEntAnomaly.setLicense(company.getLicense());
            jsEntAnomaly.setDailyCheckId(dailyCheck.getId());
            jsEntAnomaly.setAbnormalCause(abnormalCause);
            jsEntAnomaly.setAuditTrails(auditTrails);
            jsEntAnomaly.setRectifyTime(rectifyTime);
            jsEntAnomaly.setCheckResults(checkResults);
            jsEntAnomaly.setProcessResults(exprocessResults);
            if (!"2".equals(temporary)) {
                //临时存储的
                jsEntAnomaly.setDeleteFlag(2L);
            } else {
                //正式存储的
                jsEntAnomaly.setDeleteFlag(0L);
            }

            jsEntAnomaly.setCheckNumber(checkNum);
            if (jsEntAnomaly.getId() == null) {
                jsEntAnomaly.setCreateTime(new Date());
                jsEntAnomaly.setCreatorId(UserHelper.getUserId());
                jsEntAnomaly.setCreator(UserHelper.getUserInfo().getName());

                jsEntAnomalyMapper.insert(jsEntAnomaly);
            } else {
                jsEntAnomalyMapper.updateById(jsEntAnomaly);
            }

        }
    }


    @Transactional(rollbackFor = Exception.class)
    public JgDailyStandard createNewDailyStandard(JgStandard standard, JgDailyCheck dailyCheck, TcCompany company, TsDept dept) {
        JgDailyStandard dailyStandard = new JgDailyStandard();
        dailyStandard.setTemplateId(dailyCheck.getTemplateId());
        dailyStandard.setStandardId(standard.getId());
        dailyStandard.setSupCategory("1");
        dailyStandard.setSupProcess(company.getSupProcess());
        dailyStandard.setSpxsId(standard.getSpxsId());
        dailyStandard.setSupProcess(company.getSupProcess());
        dailyStandard.setCyfwId(standard.getCyfwId());
        dailyStandard.setSpscLbId(standard.getSpscLbId());
        dailyStandard.setSpscLbZlId(standard.getSpscLbZlId());
        dailyStandard.setTsspLbId(standard.getTsspLbId());
        dailyStandard.setTsspLbZlId(standard.getTsspLbZlId());
        dailyStandard.setName(standard.getName());
        dailyStandard.setSerialNum(standard.getSerialNum());
        dailyStandard.setDailyCheckId(dailyCheck.getId());
        dailyStandard.setCreateTime(new Date());
        dailyStandard.setCreatorId(UserHelper.getUserId());
        dailyStandard.setCreator(UserHelper.getUserInfo().getName());
        if (dept != null) {
            dailyStandard.setCreateDeptName(dept.getName());
            dailyStandard.setCreateDeptId(UserHelper.getUserInfo().getDeptId());
        }
        dailyStandard.setDeleteFlag(0L);
        return dailyStandard;
    }


    public void setDailyContent(String manageStatus, ContentList content, JgDailyContent dailyContent, JgCheckContent contentQuery) {
        dailyContent.setSelection("1".equals(manageStatus) ? "2" : content.getSelection());
        dailyContent.setCheckContent(content.getCheckContent());
        dailyContent.setMissingItemContent(content.getMissingItemContent());
        dailyContent.setProblemContent(content.getProblemContent());
        dailyContent.setProblemContentInput(content.getProblemContentInput());
        dailyContent.setMissingItemContentInput(content.getMissingItemContentInput());
        if ("1".equals(manageStatus)) {
            dailyContent.setScore(contentQuery.getScore());
        } else {
            if ("1".equals(content.getSelection())) {
                dailyContent.setScore(contentQuery.getYesScore());
            } else {
                dailyContent.setScore(contentQuery.getScore());
            }
        }
        if (StringUtils.isNotBlank(content.getProblemFile())
                && !StringUtils.equals(content.getProblemFile(), "undefined")
                && StringUtils.indexOf(content.getProblemFile(), "data:image") >= 0
        ) {
            //上传选择否的时候的图片,如果是data:image开头的才进行上传
            try {
                FileResultEntity filePath = FileUploadUtil.uploadImageBase64Image(content.getProblemFile(), FileUploadEnum.inspect.getPath());
                log.info("新增dailyContent的图片:{}", filePath.getFilePath());
                dailyContent.setProblemFile(filePath.getFilePath());
            } catch (Exception e) {
                log.error("新增dailyContent的图片:{}", e);
            }
        } else {
            dailyContent.setProblemFile(content.getProblemFile());
        }
    }

    /**
     * 最终保存
     *
     * @param checkId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JgDailyCheck finaSaveInfo(Long checkId, String processResults, String rectificationTimeLimit, String contactPhone) {
        JgDailyCheck dailyCheck = dailyCheckMapper.selectById(checkId);
        dailyCheck.setCheckStat("1");
        dailyCheck.setCheckTime(DateUtil.format(new Date(), "yyyy-MM-dd"));
        dailyCheckMapper.updateById(dailyCheck);
        TcCompany company = companyMapper.selectById(dailyCheck.getCompanyId());
        if (StringUtils.isNotEmpty(contactPhone)) {
            company.setContactPhone(contactPhone);
            companyMapper.updateById(company);
        }
        //如果选择的不是通过的话生成相应的后续步骤
        if ("2".equals(processResults)) {
            //责令整改
            saveRectification(rectificationTimeLimit, company, dailyCheck);
        } else if ("3".equals(processResults)) {
            //选择调查处理同时也要生成一个整改信息
            saveRectification(rectificationTimeLimit, company, dailyCheck);

            //调查处理,查看调查处理开关是否打开
            JgInvestigationSet investigationSet = jgInvestigationSetMapper.selectByCheckTypeAndProcess("2", company.getSupProcess());
            //调查处理开关打开的情况下才生成下面的内容
            if ("1".equals(investigationSet == null ? "2" : investigationSet.getCheckStatus())) {
                saveInvestigation(company, dailyCheck);
            }
        }
//        JsEntAnomaly jsEntAnomaly = jsEntAnomalyMapper.selectByCheckId(dailyCheck.getId(), "2");
//        if (jsEntAnomaly != null) {
//            jsEntAnomaly.setDeleteFlag(0L);
//            jsEntAnomalyMapper.updateById(jsEntAnomaly);
//        } else
        return dailyCheck;
    }

    /**
     * 保存调查处理
     *
     * @param company    企业信息
     * @param dailyCheck 日常检查信息
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void saveInvestigation(TcCompany company, JgDailyCheck dailyCheck) {
        //如果已经存在整改单信息说明之前保存完成了 属于流程操作错误问题不进行保存
        List<JgInvestigation> investigations = investigationMapper.selectByCheckId(dailyCheck.getId(), "2");
        JgInvestigation investigation;
        if (investigations.size() > 0) {
            investigation = investigations.get(0);
        } else {
            investigation = new JgInvestigation();
        }
        investigation.setCompanyId(company.getId());
        investigation.setCheckId(dailyCheck.getId());
        investigation.setCheckType("2");
        investigation.setCheckStatus("1");
        investigation.setCreateTime(new Date());
        investigation.setCreatorId(UserHelper.getUserId());
        investigation.setCreatorName(UserHelper.getUserInfo().getName());
        investigation.setDeleteFlag(0L);
        investigation.setCheckPersonnel(UserHelper.getUserId());//处理人员，谁检查的就是谁
        investigation.setCheckPersonnelName(UserHelper.getUserInfo().getName());
        if (investigation.getId() == null) {
            investigationMapper.insert(investigation);
        } else {
            investigationMapper.updateById(investigation);
        }
        //保存整改内容的初始信息
        List<JgDailyContent> dailyContent = jgDailyContentMapper.selectNoPassList(dailyCheck.getId());
        List<JgInvestigationContent> investigationContentList = new ArrayList<>();
        for (JgDailyContent jgDailyContent : dailyContent) {
            JgInvestigationContent investigationContent = new JgInvestigationContent();
            investigationContent.setInvestigationId(investigation.getId());
            investigationContent.setCheckType("2");
            investigationContent.setCheckContentId(jgDailyContent.getId());
            investigationContent.setCreateTime(new Date());
            investigationContent.setCreatorId(UserHelper.getUserId());
            investigationContent.setCreatorName(UserHelper.getUserInfo().getName());
            investigationContent.setDeleteFlag(0L);
            investigationContent.setSerialNum(jgDailyContent.getStandardNum());
            investigationContent.setStandardName(jgDailyContent.getStandardName());
            investigationContent.setContentNum(jgDailyContent.getSerialNum());
            investigationContent.setCheckContent(jgDailyContent.getCheckContent());
            investigationContent.setSelection(jgDailyContent.getSelection());
            investigationContent.setProblemContent(jgDailyContent.getProblemContent());
            investigationContent.setProblemFile(jgDailyContent.getProblemFile());
            investigationContent.setProblemContentInput(jgDailyContent.getProblemContentInput());
            investigationContent.setMissingItemContent(jgDailyContent.getMissingItemContent());
            investigationContent.setMissingItemContentInput(jgDailyContent.getMissingItemContentInput());
            //investigationContentMapper.insert(investigationContent);
            investigationContentList.add(investigationContent);
        }
        investigationContentMapper.batchInsert(investigationContentList);
    }

    /**
     * 保存整改信息
     *
     * @param rectificationTimeLimit 整改期限
     * @param company                企业信息
     * @param dailyCheck             日常检查信息
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void saveRectification(String rectificationTimeLimit,
                                  TcCompany company, JgDailyCheck dailyCheck) {
        //如果已经存在整改单信息说明之前保存完成了 属于流程操作错误问题不进行保存
        List<JgRectification> rectifications = rectificationMapper.selectByCheckId(dailyCheck.getId(), "2");
        JgRectification rectification;
        if (rectifications.size() > 0) {
            rectification = rectifications.get(0);
        } else {
            rectification = new JgRectification();
        }
        rectification.setCompanyId(company.getId());
        rectification.setCheckId(dailyCheck.getId());
        rectification.setCheckType("2");
        rectification.setCheckStatus("1");
        rectification.setRectificationTimeLimit(rectificationTimeLimit);
        rectification.setCreateTime(new Date());
        rectification.setCreatorId(UserHelper.getUserId());
        rectification.setCreatorName(UserHelper.getUserInfo().getName());
        rectification.setDeleteFlag(0L);
        if (rectification.getId() == null) {
            rectificationMapper.insert(rectification);
        } else {
            rectificationMapper.updateById(rectification);

        }

        //保存整改内容的初始信息

        if (!StringUtils.equals(dailyCheck.getManageStatus(), "1")) {
            //选择的不是经营异常才存储这个问题项
            List<JgDailyContent> dailyContent = jgDailyContentMapper.selectNoPassList(dailyCheck.getId());
            List<JgRectificationContent> insertContentList = new ArrayList<>();
            for (JgDailyContent jgDailyContent : dailyContent) {
                JgRectificationContent rectificationContent = new JgRectificationContent();
                rectificationContent.setRectificationId(rectification.getId());
                rectificationContent.setCheckType("2");
                rectificationContent.setCheckContentId(jgDailyContent.getId());
                rectificationContent.setCreateTime(new Date());
                rectificationContent.setCreatorId(UserHelper.getUserId());
                rectificationContent.setCreatorName(UserHelper.getUserInfo().getName());
                rectificationContent.setDeleteFlag(0L);
                rectificationContent.setSerialNum(jgDailyContent.getStandardNum());
                rectificationContent.setStandardName(jgDailyContent.getStandardName());
                rectificationContent.setContentNum(jgDailyContent.getSerialNum());
                rectificationContent.setCheckContent(jgDailyContent.getCheckContent());
                rectificationContent.setSelection(jgDailyContent.getSelection());
                rectificationContent.setProblemContent(jgDailyContent.getProblemContent());
                rectificationContent.setProblemFile(jgDailyContent.getProblemFile());
                rectificationContent.setProblemContentInput(jgDailyContent.getProblemContentInput());
                rectificationContent.setMissingItemContentInput(jgDailyContent.getMissingItemContentInput());
                rectificationContent.setMissingItemContent(jgDailyContent.getMissingItemContent());
//            rectificationContentMapper.insert(rectificationContent);
                insertContentList.add(rectificationContent);
            }
            if (!insertContentList.isEmpty()) {
                rectificationContentMapper.batchInsert(insertContentList);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveEntAnomaly(TcCompany company,
                               JgDailyCheck dailyCheck, String abnormalCause,
                               String auditTrails, String rectifyTime, String checkResults, String exprocessResults) {
        JsEntAnomaly jsEntAnomaly = jsEntAnomalyMapper.selectByCheckId(dailyCheck.getId(), "2");
        if (jsEntAnomaly == null) {
            jsEntAnomaly = new JsEntAnomaly();
        }
        jsEntAnomaly.setCheckType("2");
        jsEntAnomaly.setCompanyId(company.getId());
        jsEntAnomaly.setCompanyName(company.getCompanyName());
        jsEntAnomaly.setCreditCode(company.getCreditCode());
        jsEntAnomaly.setLicense(company.getLicense());
        jsEntAnomaly.setDailyCheckId(dailyCheck.getId());
        jsEntAnomaly.setAbnormalCause(abnormalCause);
        jsEntAnomaly.setAuditTrails(auditTrails);
        jsEntAnomaly.setRectifyTime(rectifyTime);
        jsEntAnomaly.setCheckResults(checkResults);
        jsEntAnomaly.setProcessResults(exprocessResults);
        //正式存储的
        jsEntAnomaly.setDeleteFlag(0L);
        if (jsEntAnomaly.getId() == null) {
            jsEntAnomaly.setCreateTime(new Date());
            jsEntAnomaly.setCreatorId(UserHelper.getUserId());
            jsEntAnomaly.setCreator(UserHelper.getUserInfo().getName());
            jsEntAnomalyMapper.insert(jsEntAnomaly);
        } else {
            jsEntAnomalyMapper.updateById(jsEntAnomaly);
        }
    }

    /**
     * 保存异常信息
     *
     * @param company          企业信息
     * @param dailyCheck       日常检查表
     * @param abnormalCause    异常原因
     * @param auditTrails      异常核查记录
     * @param rectifyTime      异常整改时间
     * @param checkResults     异常检查结果
     * @param exprocessResults 异常处理结果
     * @param temporary        等于2才是正式保存
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveEntAnomalyHi(TcCompany company,
                                 JgDailyCheck dailyCheck, String abnormalCause,
                                 String auditTrails, String rectifyTime, String checkResults, String exprocessResults, String rectificationTimeLimit, String temporary) {
        JsEntAnomaly jsEntAnomaly = jsEntAnomalyMapper.selectByCheckId(dailyCheck.getId(), "2");
        if (jsEntAnomaly == null) {
            jsEntAnomaly = new JsEntAnomaly();
        }
        jsEntAnomaly.setCheckType("2");
        jsEntAnomaly.setCompanyId(company.getId());
        jsEntAnomaly.setCompanyName(company.getCompanyName());
        jsEntAnomaly.setCreditCode(company.getCreditCode());
        jsEntAnomaly.setLicense(company.getLicense());
        jsEntAnomaly.setDailyCheckId(dailyCheck.getId());
        jsEntAnomaly.setAbnormalCause(abnormalCause);
        jsEntAnomaly.setAuditTrails(auditTrails);
        jsEntAnomaly.setRectifyTime(rectifyTime);
        jsEntAnomaly.setCheckResults(checkResults);
        jsEntAnomaly.setProcessResults(exprocessResults);
        if (!"2".equals(temporary)) {
            //临时存储的
            jsEntAnomaly.setDeleteFlag(2L);
        } else {
            //正式存储的
            jsEntAnomaly.setDeleteFlag(0L);
        }
        if (jsEntAnomaly.getId() == null) {
            jsEntAnomaly.setCreateTime(new Date());
            jsEntAnomaly.setCreatorId(UserHelper.getUserId());
            jsEntAnomaly.setCreator(UserHelper.getUserInfo().getName());
            jsEntAnomalyMapper.insert(jsEntAnomaly);
        } else {
            jsEntAnomalyMapper.updateById(jsEntAnomaly);
        }
        if (!"2".equals(temporary)) {
            //临时存储的先不存储下面的检查内容
            return;
        }
        //删除原来填写的检查内容信息，检查异常之后
        //List<Map<String, Object>> dailyStandardList = jgDailyStandardMapper.selectDailyCheckId(dailyCheck.getId());
        List<Map<String, Object>> dailyContentList = jgDailyContentMapper.selectByDailyCheckId(dailyCheck.getId());
        int checkNum = 0;
        List<Object> dailyIdList = new ArrayList<>();
        for (Map<String, Object> stringObjectMap : dailyContentList) {
            if ("2".equals(stringObjectMap.get("SELECTION").toString())) {
                checkNum = checkNum + 1;
            }
            // dailyIdList.add(stringObjectMap.get("ID"));
        }
        //jgDailyContentMapper.updateSelectionByIds(dailyIdList,"2");

        jsEntAnomaly.setCheckNumber(checkNum);
        jsEntAnomalyMapper.updateById(jsEntAnomaly);
    }

    @Transactional(rollbackFor = Exception.class)
    public void uploadResultRecord(Long checkId, MultipartFile imgFile, String type) throws Exception {
        JgDailyCheck dailyCheck = dailyCheckMapper.selectById(checkId);
        if (imgFile != null && StringUtils.isNoneBlank(imgFile.getOriginalFilename())) {
            FileResultEntity fileResultEntity = FileUploadUtil.uploadImage(imgFile, FileUploadEnum.doubleRandomInspect.getPath());
            if ("1".equals(type)) {
                dailyCheck.setCheckItemTableUrl(fileResultEntity.getFilePath());
            } else if ("2".equals(type)) {
                dailyCheck.setResultRecordUrl(fileResultEntity.getFilePath());
            }
            dailyCheckMapper.updateById(dailyCheck);
        }
    }


    @Transactional(rollbackFor = Exception.class)
    public String saveCheckInform(Long checkId, Long checkPerson1Id, Long checkPerson2Id, String checkAddress, String notifyMatters, String isAvoid, String companySignFile, String checkPerson1SignFile, String checkPerson2SignFile, String informFile) {
        JgDailyCheck dailyCheck = dailyCheckMapper.selectById(checkId);
        if (dailyCheck == null) {
            throw new RuntimeException("请先在检查内容中进行操作");
        }
        JgCheckInform jgCheckInform = jgCheckInformMapper.selectByDailyCheckId(dailyCheck.getId());
        TcCompany company = companyMapper.selectById(dailyCheck.getCompanyId());
        if (jgCheckInform == null) {
            jgCheckInform = new JgCheckInform();
            jgCheckInform.setCreateTime(new Date());
            jgCheckInform.setDailyCheckId(dailyCheck.getId());
        }
        jgCheckInform.setCompanyName(company.getCompanyName());
        jgCheckInform.setAddress(company.getAddress());
        jgCheckInform.setCheckPerson1Id(checkPerson1Id);
        if (checkPerson1Id != null) {
            TsUser user1 = userMapper.selectById(checkPerson1Id);
            jgCheckInform.setCheckPerson1Name(user1.getName());
        }
        jgCheckInform.setCheckPerson2Id(checkPerson2Id);
        if (checkPerson2Id != null) {
            TsUser user2 = userMapper.selectById(checkPerson2Id);
            jgCheckInform.setCheckPerson2Name(user2.getName());
        }
        jgCheckInform.setCheckTime(DateUtil.format(new Date(), "yyyy-MM-dd"));
        jgCheckInform.setCheckAddr(checkAddress);
        jgCheckInform.setNotifyMatters(notifyMatters);
        jgCheckInform.setIsAvoid(isAvoid);
        FileResultEntity informFileUrl = null;
        try {
            FileResultEntity companySignUrl = FileUploadUtil.uploadSVGBase64Image(companySignFile, FileUploadEnum.doubleRandomInspect.getPath());
            jgCheckInform.setCompanySign(companySignUrl.getFilePath());
            FileResultEntity checkPerson1SignFileUrl = FileUploadUtil.uploadSVGBase64Image(checkPerson1SignFile, FileUploadEnum.doubleRandomInspect.getPath());
            jgCheckInform.setCheckPerson1Sign(checkPerson1SignFileUrl.getFilePath());
            FileResultEntity checkPerson2SignFileUrl = FileUploadUtil.uploadSVGBase64Image(checkPerson2SignFile, FileUploadEnum.doubleRandomInspect.getPath());
            jgCheckInform.setCheckPerson2Sign(checkPerson2SignFileUrl.getFilePath());
            informFileUrl = FileUploadUtil.uploadImageBase64Image(informFile, FileUploadEnum.doubleRandomInspect.getPath());
            jgCheckInform.setInformUrl(informFileUrl.getFilePath());
        } catch (Exception e) {
            throw new RuntimeException("上传文件失败");
        }

        if (jgCheckInform.getId() == null) {
            jgCheckInformMapper.insert(jgCheckInform);
        } else {
            jgCheckInformMapper.updateById(jgCheckInform);
        }
        dailyCheck.setInformId(jgCheckInform.getId());
        dailyCheck.setInformUrl(informFileUrl.getFilePath());
        dailyCheckMapper.updateById(dailyCheck);
        return dailyCheck.getInformUrl();
    }

    public Map<String, Object> getCheckResultInfo(Long checkId) {
        Map<String, Object> result = new HashMap<>();
        //检查结果
        Map<String, Object> checkInfo = new HashMap<>();
        //获取和各项，不合格项，合理缺项比例
        JgDailyCheck dailyCheck = dailyCheckMapper.selectById(checkId);
        List<Map<String, Object>> contentList = jgDailyContentMapper.selectByDailyCheckId(checkId);
        int hege = 0;
        int buhege = 0;
        int heliquexiang = 0;

        if ("1".equals(dailyCheck.getManageStatus())) {
            JsEntAnomaly entAnomaly = jsEntAnomalyMapper.selectByCheckId(dailyCheck.getId(), "2");
            checkInfo.put("CHECK_RESULTS", entAnomaly.getCheckResults());
            checkInfo.put("ECHARTS_QUALIFIED", hege);
            checkInfo.put("ECHARTS_NOQUALIFIED", entAnomaly.getCheckNumber());
            checkInfo.put("ECHARTS_MISSING_ITEM", heliquexiang);
        } else {
            checkInfo.put("CHECK_RESULTS", dailyCheck.getCheckResult());
            // is '选择项：1是、2否、3合理缺项'
            for (Map<String, Object> content : contentList) {
                String selection = content.get("SELECTION") + "";
                switch (selection) {
                    case "1":
                        hege++;
                        break;
                    case "2":
                        buhege++;
                        break;
                    case "3":
                        heliquexiang++;
                        break;
                }
            }
            checkInfo.put("ECHARTS_QUALIFIED", hege);
            checkInfo.put("ECHARTS_NOQUALIFIED", buhege);
            checkInfo.put("ECHARTS_MISSING_ITEM", heliquexiang);
        }

        //处理结果：1通过检查，2责令整改，3调查处理
        checkInfo.put("PROCESS_RESULTS", dailyCheck.getProcessResults());
        //整改完成时限 获取整改信息
        List<JgRectification> rectificationList = rectificationMapper.selectByCheckId(dailyCheck.getId(), "1");
        checkInfo.put("RECTIFICATION_TIME_LIMIT", dailyCheck.getRectificationTimeLimit());
        //其他问题
        checkInfo.put("OTHER_PROBLEM", dailyCheck.getOtherProblem());
        //监督检查要点表url
        checkInfo.put("CHECK_ITEM_TABLEURL", dailyCheck.getCheckItemTableUrl());
        //结果记录表url
        checkInfo.put("RESULT_RECORD_URL", dailyCheck.getResultRecordUrl());
        result.put("checkInfo", checkInfo);
        Map<String, Object> companyInfo = selectCompanyInfo(dailyCheck.getCompanyId());

        //告知页
        JgCheckInform jgCheckInform = jgCheckInformMapper.selectByDailyCheckId(checkId);
        if (jgCheckInform != null) {
            companyInfo.put("INFORM_URL", jgCheckInform.getInformUrl());
        }
        result.put("baseInfo", companyInfo);
        if ("1".equals(dailyCheck.getManageStatus())) {
            //异常
            List<Map<String, Object>> checkStandardList = templateMapper.selectStandardListByTemplateId(dailyCheck.getTemplateId(), "1");
            result.put("standardList", checkStandardList);
        } else {
            List<Map<String, Object>> standardList = jgDailyStandardMapper.selectDailyCheckId(checkId);
            result.put("standardList", standardList);
        }
        return result;
    }
}
